<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TTS服务数据分析</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .dashboard {
            display: grid;
            grid-template-columns: 1fr;
            gap: 20px;
            margin-top: 30px;
        }
        .card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            padding: 20px;
        }
        h2 {
            color: #444;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
        .stats-container {
            display: flex;
            justify-content: space-around;
            flex-wrap: wrap;
            margin-bottom: 20px;
        }
        .stat-item {
            text-align: center;
            padding: 20px;
            background-color: #f9f9f9;
            border-radius: 8px;
            width: 200px;
            margin: 10px;
        }
        .stat-number {
            font-size: 36px;
            font-weight: bold;
            color: #165DFF;
        }
        .stat-label {
            font-size: 16px;
            color: #666;
            margin-top: 10px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        th {
            background-color: #f9f9f9;
            font-weight: bold;
            color: #333;
        }
        tr:hover {
            background-color: #f5f5f5;
        }
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }
        .pagination button {
            margin: 0 5px;
            padding: 8px 16px;
            border: 1px solid #ddd;
            background-color: white;
            cursor: pointer;
            border-radius: 4px;
        }
        .pagination button:hover {
            background-color: #f0f0f0;
        }
        .pagination button.active {
            background-color: #165DFF;
            color: white;
            border-color: #165DFF;
        }
        .refresh-btn {
            background-color: #165DFF;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-bottom: 20px;
        }
        .refresh-btn:hover {
            background-color: #0e4fd8;
        }
        .tab-container {
            display: flex;
            margin-bottom: 20px;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            background-color: #f0f0f0;
            border: 1px solid #ddd;
            border-right: none;
        }
        .tab:last-child {
            border-right: 1px solid #ddd;
        }
        .tab.active {
            background-color: white;
            font-weight: bold;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .feedback-positive {
            color: green;
        }
        .feedback-negative {
            color: red;
        }
        .text-truncate {
            max-width: 300px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        /* 图表样式 */
        .chart-container {
            height: 300px;
            margin: 20px 0;
        }
    </style>
    <!-- 引入Chart.js用于数据可视化 -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <h1>TTS服务数据分析平台</h1>
    <button class="refresh-btn" onclick="refreshAllData()">🔄 刷新数据</button>
    
    <div class="dashboard">
        <!-- 统计概览卡片 -->
        <div class="card">
            <h2>数据概览</h2>
            <div class="stats-container">
                <div class="stat-item">
                    <div class="stat-number" id="totalLikes">0</div>
                    <div class="stat-label">总点赞数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number" id="totalDislikes">0</div>
                    <div class="stat-label">总点踩数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number" id="totalFeedback">0</div>
                    <div class="stat-label">总反馈数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number" id="totalAccess">0</div>
                    <div class="stat-label">总访问次数</div>
                </div>
            </div>
            <div class="chart-container">
                <canvas id="feedbackChart"></canvas>
            </div>
        </div>
        
        <!-- 数据详情标签页 -->
        <div class="card">
            <h2>数据详情</h2>
            <div class="tab-container">
                <div class="tab active" onclick="switchTab('feedback')">反馈记录</div>
                <div class="tab" onclick="switchTab('access')">访问记录</div>
            </div>
            
            <!-- 反馈记录内容 -->
            <div class="tab-content active" id="feedback-content">
                <table id="feedbackTable">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>文本ID</th>
                            <th>评分</th>
                            <th>反馈内容</th>
                            <th>提交时间</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- 反馈数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
                <div class="pagination" id="feedbackPagination">
                    <!-- 分页按钮将通过JavaScript动态加载 -->
                </div>
            </div>
            
            <!-- 访问记录内容 -->
            <div class="tab-content" id="access-content">
                <table id="accessTable">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>IP地址</th>
                            <th>输入文本</th>
                            <th>选择音色</th>
                            <th>语速</th>
                            <th>访问时间</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- 访问数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
                <div class="pagination" id="accessPagination">
                    <!-- 分页按钮将通过JavaScript动态加载 -->
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentFeedbackPage = 1;
        let currentAccessPage = 1;
        const pageSize = 10;
        let feedbackChart = null;
        
        // 初始化图表
        function initChart() {
            const ctx = document.getElementById('feedbackChart').getContext('2d');
            feedbackChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ['点赞', '点踩'],
                    datasets: [{
                        label: '反馈统计',
                        data: [0, 0],
                        backgroundColor: [
                            'rgba(75, 192, 192, 0.6)',
                            'rgba(255, 99, 132, 0.6)'
                        ],
                        borderColor: [
                            'rgba(75, 192, 192, 1)',
                            'rgba(255, 99, 132, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                stepSize: 1
                            }
                        }
                    }
                }
            });
        }
        
        // 更新图表数据
        function updateChart(likes, dislikes) {
            if (feedbackChart) {
                feedbackChart.data.datasets[0].data = [likes, dislikes];
                feedbackChart.update();
            }
        }
        
        // 获取并更新统计数据
        async function fetchAndUpdateStats() {
            try {
                const response = await fetch('http://localhost:8000/api/feedback/stats');
                const data = await response.json();
                if (data.status === 'success') {
                    document.getElementById('totalLikes').textContent = data.data.likes;
                    document.getElementById('totalDislikes').textContent = data.data.dislikes;
                    document.getElementById('totalFeedback').textContent = data.data.total;
                    
                    // 更新图表
                    updateChart(data.data.likes, data.data.dislikes);
                }
            } catch (error) {
                console.error('获取统计数据失败:', error);
            }
            
            // 获取总访问次数（这里简化处理，实际应该添加一个专门的API）
            try {
                const response = await fetch('http://localhost:8000/api/access-log/recent?limit=10000');
                const data = await response.json();
                if (data.status === 'success') {
                    document.getElementById('totalAccess').textContent = data.data.length;
                }
            } catch (error) {
                console.error('获取访问数据失败:', error);
            }
        }
        
        // 获取并显示反馈记录
        async function fetchAndDisplayFeedback(page = 1) {
            try {
                // 注意：这里我们使用大限制来获取所有数据，然后在前端进行分页
                // 实际项目中应该有专门的分页API
                const response = await fetch('http://localhost:8000/api/feedback/recent?limit=10000');
                const data = await response.json();
                if (data.status === 'success') {
                    const feedbackData = data.data;
                    displayFeedbackData(feedbackData, page);
                    renderFeedbackPagination(feedbackData.length);
                }
            } catch (error) {
                console.error('获取反馈数据失败:', error);
            }
        }
        
        // 获取并显示访问记录
        async function fetchAndDisplayAccess(page = 1) {
            try {
                // 注意：这里我们使用大限制来获取所有数据，然后在前端进行分页
                // 实际项目中应该有专门的分页API
                const response = await fetch('http://localhost:8000/api/access-log/recent?limit=10000');
                const data = await response.json();
                if (data.status === 'success') {
                    const accessData = data.data;
                    displayAccessData(accessData, page);
                    renderAccessPagination(accessData.length);
                }
            } catch (error) {
                console.error('获取访问数据失败:', error);
            }
        }
        
        // 显示反馈数据
        function displayFeedbackData(data, page) {
            const tableBody = document.getElementById('feedbackTable').querySelector('tbody');
            tableBody.innerHTML = '';
            
            const startIndex = (page - 1) * pageSize;
            const endIndex = Math.min(startIndex + pageSize, data.length);
            const pageData = data.slice(startIndex, endIndex);
            
            pageData.forEach((item, index) => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${startIndex + index + 1}</td>
                    <td>${item.text_id}</td>
                    <td class="${item.rating === 1 ? 'feedback-positive' : 'feedback-negative'}">
                        ${item.rating === 1 ? '👍 点赞' : '👎 点踩'}
                    </td>
                    <td class="text-truncate" title="${item.content}">${item.content || '-'}</td>
                    <td>${new Date(item.created_at).toLocaleString()}</td>
                `;
                tableBody.appendChild(row);
            });
        }
        
        // 显示访问数据
        function displayAccessData(data, page) {
            const tableBody = document.getElementById('accessTable').querySelector('tbody');
            tableBody.innerHTML = '';
            
            const startIndex = (page - 1) * pageSize;
            const endIndex = Math.min(startIndex + pageSize, data.length);
            const pageData = data.slice(startIndex, endIndex);
            
            pageData.forEach((item, index) => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${startIndex + index + 1}</td>
                    <td>${item.ip}</td>
                    <td class="text-truncate" title="${item.text}">${item.text || '-'}</td>
                    <td>${item.voice}</td>
                    <td>${item.speed}</td>
                    <td>${new Date(item.created_at).toLocaleString()}</td>
                `;
                tableBody.appendChild(row);
            });
        }
        
        // 渲染反馈分页
        function renderFeedbackPagination(totalItems) {
            const totalPages = Math.ceil(totalItems / pageSize);
            const paginationContainer = document.getElementById('feedbackPagination');
            paginationContainer.innerHTML = '';
            
            // 添加首页按钮
            addPaginationButton(paginationContainer, 1, '首页', currentFeedbackPage === 1, fetchAndDisplayFeedback);
            
            // 添加页码按钮
            const maxVisiblePages = 5;
            let startPage = Math.max(1, currentFeedbackPage - Math.floor(maxVisiblePages / 2));
            let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
            
            if (endPage - startPage + 1 < maxVisiblePages) {
                startPage = Math.max(1, endPage - maxVisiblePages + 1);
            }
            
            for (let i = startPage; i <= endPage; i++) {
                addPaginationButton(paginationContainer, i, i.toString(), currentFeedbackPage === i, fetchAndDisplayFeedback);
            }
            
            // 添加末页按钮
            addPaginationButton(paginationContainer, totalPages, '末页', currentFeedbackPage === totalPages, fetchAndDisplayFeedback);
        }
        
        // 渲染访问分页
        function renderAccessPagination(totalItems) {
            const totalPages = Math.ceil(totalItems / pageSize);
            const paginationContainer = document.getElementById('accessPagination');
            paginationContainer.innerHTML = '';
            
            // 添加首页按钮
            addPaginationButton(paginationContainer, 1, '首页', currentAccessPage === 1, fetchAndDisplayAccess);
            
            // 添加页码按钮
            const maxVisiblePages = 5;
            let startPage = Math.max(1, currentAccessPage - Math.floor(maxVisiblePages / 2));
            let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
            
            if (endPage - startPage + 1 < maxVisiblePages) {
                startPage = Math.max(1, endPage - maxVisiblePages + 1);
            }
            
            for (let i = startPage; i <= endPage; i++) {
                addPaginationButton(paginationContainer, i, i.toString(), currentAccessPage === i, fetchAndDisplayAccess);
            }
            
            // 添加末页按钮
            addPaginationButton(paginationContainer, totalPages, '末页', currentAccessPage === totalPages, fetchAndDisplayAccess);
        }
        
        // 添加分页按钮
        function addPaginationButton(container, pageNum, text, isActive, callback) {
            const button = document.createElement('button');
            button.textContent = text;
            if (isActive) {
                button.classList.add('active');
                button.disabled = true;
            }
            button.addEventListener('click', () => {
                if (callback === fetchAndDisplayFeedback) {
                    currentFeedbackPage = pageNum;
                } else {
                    currentAccessPage = pageNum;
                }
                callback(pageNum);
            });
            container.appendChild(button);
        }
        
        // 切换标签页
        function switchTab(tabName) {
            // 隐藏所有标签内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            
            // 移除所有标签的活跃状态
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 显示选中的标签内容
            document.getElementById(`${tabName}-content`).classList.add('active');
            
            // 设置选中的标签为活跃状态
            document.querySelector(`.tab[onclick="switchTab('${tabName}')"]`).classList.add('active');
        }
        
        // 刷新所有数据
        function refreshAllData() {
            fetchAndUpdateStats();
            fetchAndDisplayFeedback(currentFeedbackPage);
            fetchAndDisplayAccess(currentAccessPage);
        }
        
        // 页面加载时初始化
        window.addEventListener('load', () => {
            initChart();
            refreshAllData();
        });
    </script>
</body>
</html>